import {magic} from '@lexmis/magic-ui/pc';
import Vue from 'vue';
export const EventBus = new Vue();
export function toDate(v, format){
	format = format || 'yyyy-MM-dd HH:mm';
	if(!v) return '';
	let d = v;
	if(typeof v === 'string'){
		if(v.indexOf('/Date(') > -1){
			d = new Date(parseInt(v.replace('/Date(', '').replace(')/', ''), 10));
		}else d = new Date(Date.parse(v.replace(/-/g, '/').replace('T', ' ').split('.')[0]));
	}else{
		d = new Date(v);
	}
	let o = {
		'M+':d.getMonth() + 1,
		'd+':d.getDate(),
		'h+':d.getHours(),
		'H+':d.getHours(),
		'm+':d.getMinutes(),
		's+':d.getSeconds(),
		'q+':Math.floor((d.getMonth() + 3) / 3),
		S:d.getMilliseconds(),
	};
	if(/(y+)/.test(format)){
		format = format.replace(RegExp.$1, (d.getFullYear() + '').substr(4 - RegExp.$1.length));
	}
	for(let k in o){
		if(new RegExp('(' + k + ')').test(format)){
			format = format.replace(
				RegExp.$1,
				RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length),
			);
		}
	}
	return format;
}
export function thousandsFormat(num){
	if(!num && num !== 0) return '';
	const numArr = num.toString().split('.');
	numArr[0] = numArr[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
	return numArr.join('.');
}
export function mergeNumberOfExps(expressions){
	if(!Array.isArray(expressions)) return [];
	const res = [];
	const isNumChar = (n) => /^[\d|\.]$/.test(n);
	for(let i = 0; i < expressions.length; i++){
		if(i > 0 && isNumChar(expressions[i - 1]) && isNumChar(expressions[i])){
			res[res.length - 1] += expressions[i];
			continue;
		}
		res.push(expressions[i]);
	}
	return res;
}
export function toRPN(exps){
	const s1 = []; // 符号栈
	const s2 = []; // 输出栈
	const getTopVal = (stack) => (stack.length > 0 ? stack[stack.length - 1] : null);
	const levelCompare = (c1, c2) => {
		const getIndex = (c) => ['+-', '×÷', '()'].findIndex((t) => t.includes(c));
		return getIndex(c1) - getIndex(c2);
	};
	exps.forEach((t) => {
		if(typeof t === 'string' && Number.isNaN(Number(t))){
            // 是符号
			if(t === '('){
				s1.push(t);
			}else if(t === ')'){
				let popVal;
				do{
					popVal = s1.pop();
					popVal !== '(' && s2.push(popVal);
				}while(s1.length && popVal !== '(');
			}else{
				let topVal = getTopVal(s1);
				if(!topVal){
                    // s1 为空 直接push
					s1.push(t);
				}else{
					while(topVal && topVal !== '(' && levelCompare(topVal, t) >= 0){
                        // 优先级 >= t 弹出到s2
						s2.push(s1.pop());
						topVal = getTopVal(s1);
					}
					s1.push(t);
				}
			}
			return;
		}
		s2.push(t); // 数字直接入栈
	});
	while(s1.length){
		s2.push(s1.pop());
	}
	return s2;
}
export function calcRPN(rpnExps){
	rpnExps = rpnExps.concat();
	const calc = (x, y, type) => {
		const a1 = Number(x);
		const a2 = Number(y);
		switch(type){
			case '+':
				return a1 + a2;
			case '-':
				return a1 - a2;
			case '×':
				return a1 * a2;
			case '÷':
				return a1 / a2;
		}
	};
	for(let i = 2; i < rpnExps.length; i++){
		if('+-×÷'.includes(rpnExps[i])){
			const val = calc(rpnExps[i - 2], rpnExps[i - 1], rpnExps[i]);
			rpnExps.splice(i - 2, 3, val);
			i = i - 2;
		}
	}
	return rpnExps[0];
}
export function debounce(func, gap){
	let timer;
	return function(){
		timer && clearTimeout(timer);
		timer = setTimeout(() => {
			func.apply(this, arguments);
		}, gap);
	};
}
export function getScriptFunc(str){
	let func = null;
	try{
		func = eval(str);
		return func;
	}catch(error){
		console.log(error);
		return false;
	}
}
export function storageGet(key){
	key = window.localStorage + key;
	const keyName = window.localStorage.getItem(key);
	if(keyName === null){
		return null;
	}
	const valArr = keyName.split('|');
	const getDataType = valArr[valArr.length - 1];
	valArr.splice(valArr.length - 1, 1);
	let val = valArr.join('');
	if(getDataType === 'Number'){
		val = parseInt(val);
	}else if(getDataType === 'Boolean'){
		if(val === 'true'){
			val = true;
		}else{
			val = false;
		}
	}else if(getDataType === 'Array' || getDataType === 'Object' || getDataType === 'Null'){
		val = JSON.parse(val);
	}
	return val;
}
export function storageSet(obj){
	for(const i in obj){
		cacheItem(i, obj[i]);
	}

	function cacheItem(key, val){
		key = 'commonUtils_' + key;
		const valType = typeof val;
		let valConstructor = '';
		if(val !== null){
			valConstructor = val.constructor;
		}
		if(valType === 'string' || valType === 'number' || valType === 'boolean'){
			if(valConstructor === String){
				val = val + '|String';
			}else if(valConstructor === Number){
				val = val + '|Number';
			}else if(valConstructor === Boolean){
				val = val + '|Boolean';
			}
			window.localStorage.setItem(key, val);
		}else if(valType === 'object'){
			if(val === null){
				val = JSON.stringify(val) + '|Null';
				window.localStorage.setItem(key, val);
			}else{
				if(valConstructor === Array){
					val = JSON.stringify(val) + '|Array';
				}else if(valConstructor === Object){
					val = JSON.stringify(val) + '|Object';
				}
				window.localStorage.setItem(key, val);
			}
		}
	}
}
export function cloneDeep(obj, hash = new WeakMap()){
	// 如果是原始值，直接返回
	if(obj === null || typeof obj !== 'object') return obj;
	// 处理循环引用
	if(hash.has(obj)) return hash.get(obj);
	const result = Array.isArray(obj) ? [] : {};
    // 防止循环引用
	hash.set(obj, result);

	for(const key in obj){
		if(Object.prototype.hasOwnProperty.call(obj, key)){
			// 递归深拷贝
			result[key] = cloneDeep(obj[key], hash);
		}
	}
	// 处理特殊类型：Date, RegExp等
	if(obj instanceof Date) return new Date(obj);
	if(obj instanceof RegExp) return new RegExp(obj);

	return result;
}
export function t(key){
	// lexmis.core.magic.view.render.xxx
	return magic.core.translate(key);
}